package com.huazi.ucenter.controller;


import com.aliyuncs.utils.StringUtils;
import com.huazi.commonutils.CommentResult;
import com.huazi.ucenter.entity.Captcha;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shkstart
 * @create 2021-03-27 21:47
 */
@Controller
@CrossOrigin
@RequestMapping("/ucenter/code")
public class CaptchaController {
    @PostMapping("/getCheckCode")
    public String getCheckCode(){
        //返回验证码图片的map
        Map<String,Object> map= Captcha.getImageCode(90,40);
        // session 存入验证码和时间
        HttpSession session = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getSession();
        session.setAttribute("check", map.get("code").toString().toLowerCase());

        // response
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse();
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg"); // 这里要指定响应的类型
        OutputStream outs = null;
        try {
            outs = response.getOutputStream();
            ImageIO.write((BufferedImage) map.get("image"), "jpg", outs);
        } catch (IOException e) {
            System.out.println("CaptchaController.imageCode:图片验证码流输出异常:"+e.getMessage());
        } finally {
            if (outs != null) {
                try {
                    outs.flush();
                    outs.close();
                } catch (IOException e) {
                    System.out.println("CaptchaController.imageCode:图片验证码流关闭异常:"+e.getMessage());
                }
            }
        }
        return null;
    }
    @GetMapping(value = "image/check/{check}")
    @ResponseBody
    public CommentResult checkCode(@PathVariable("check") String check) {
        // session 验证码信息（这里是抽象到BaseController的一个获取方法）
        HttpSession session = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getSession();
        Object simpleCaptcha = session.getAttribute("check"); // 验证码信息
        if(check.equals(simpleCaptcha))
            return CommentResult.getOK();
        return CommentResult.getError().data("code","验证码错误");
    }

    /**
     * 检查会话验证码信息是否正确（这个我是放到service中的）
     *
     * @param checkCode 前台的验证码参数
     * @param captcha session的验证码
     * @param createTime 验证码创建时间
     * @return
     */
//    private Map<String, String> checkCode(String checkCode, String captcha, Long createTime) {
//        Date now = new Date();
//        Map<String,String> map=new HashMap<>();
////        logger.debug(String.format("CaptchaController.checkCode:图片验证码J检查:checkCode=%s, captcha=%s", checkCode, captcha));
//        if (StringUtils.isEmpty(checkCode) || StringUtils.isEmpty(captcha) || !(checkCode.equalsIgnoreCase(captcha))) {
//            map.put("error","图形验证码错误");
//            return map;
//        } else if ((now.getTime() - createTime) > 5 * 60 * 1000) {
//            // 验证码有效时长为5分钟
//            map.put("error","验证码已失效");
//            return map;
//        } else {
//            map.put("ok","ok");
//            return map;
//        }
//    }
}
